import requests
from datetime import datetime

# 假设这是后台 API 的 URL，你需要替换为实际的 URL
API_URL = "http://127.0.0.1:5000/api/query_dwzb_eta"
# 假设这是提交数据的 API URL
SUBMIT_API_URL = "http://127.0.0.1:5000/api/daily_stats"

def process_api_data():
    try:
        # 手动设置查询参数，可根据实际情况修改
        raw_date = "2025-06-07"  # 示例日期
        date_obj = datetime.strptime(raw_date, "%Y-%m-%d")
        formatted_date = date_obj.strftime("%Y%m%d")
        shift = "D"  # 示例班次
        product = "TW210-216C"  # 示例产品

        form_data = {
            "query_date": formatted_date,
            "shift": shift,
            "product": product
        }

        # 发送 POST 请求到 API
        response = requests.post(API_URL, json=form_data)

        # 检查响应状态码
        if response.status_code == 200:
            # 解析 JSON 数据
            data = response.json()
            aggtj_data = data.get('aggtj_data', [])
            sumbin_data = data.get('sumbin_data', [])
##            print(aggtj_data)
##            print(sumbin_data)

            # 计算总产量
            total_output = sum(item.get('total_sum_ivgrade', 0) for item in aggtj_data)

            # 计算正常产出
            normal_output = sum(item.get('total_sum_ivgrade', 0) for item in aggtj_data if 'Eta' in item.get('Class', '') and 'Eta Fail' not in item.get('Class', ''))

            # 计算正常产出占比
            normal_rate = (normal_output / total_output * 100) if total_output else 0

            # 计算平均效率
            eta_items = [item for item in aggtj_data if 'Eta' in item.get('Class', '')]
            avg_efficiency_numerator = sum(item.get('total_sum_ivgrade', 0) * item.get('etacs', 0) for item in eta_items)
            avg_efficiency = (avg_efficiency_numerator / normal_output) if normal_output else 0

            # 计算入库效率
            valid_eta_items = [item for item in aggtj_data if 'Eta' in item.get('Class', '') and 'Eta Fail' not in item.get('Class', '')]
            # 修改前: storage_efficiency_numerator = sum(item.get('total_sum_ivgrade', 0) * float(item.get('Class', '').replace('Eta', '')) for item in valid_eta_items)
            def convert_to_float(class_str):
                cleaned_str = class_str.replace('Eta', '').replace('%', '')
                try:
                    return float(cleaned_str) if '%' in class_str else float(cleaned_str)
                except ValueError:
                    return 0

            storage_efficiency_numerator = sum(item.get('total_sum_ivgrade', 0) * convert_to_float(item.get('Class', '')) for item in valid_eta_items)
            storage_efficiency = (storage_efficiency_numerator / normal_output) if normal_output else 0

            # 计算合并档产出
            eta_classes = sorted([item for item in aggtj_data if 'Eta' in item.get('Class', '') and 'Eta Fail' not in item.get('Class', '')], key=lambda x: x.get('Class', ''))
            merge_classes = ['UNG', 'IRev2-B', 'Rsh-B']
            if eta_classes:
                merge_classes.append(eta_classes[0].get('Class', ''))
            merge_output = sum(item.get('total_sum_ivgrade', 0) for item in aggtj_data if any(cls in item.get('Class', '') for cls in merge_classes))
            merge_rate = (merge_output / total_output * 100) if total_output else 0

            # 计算漏电合并档产出
            leak_output = sum(item.get('total_sum_ivgrade', 0) for item in aggtj_data if item.get('Class', '') == 'IRev2-B')
            leak_output_rate = (leak_output / total_output * 100) if total_output else 0

            # 计算漏电失效产出
            leak_fail = sum(item.get('total_sum_ivgrade', 0) for item in aggtj_data if item.get('Class', '') == 'IRev2 Fail')
            leak_fail_rate = (leak_fail / total_output * 100) if total_output else 0

            # 计算 DLCC 产出
            DLCC = sum(item.get('quantity', 0) for item in sumbin_data if item.get('binn') == 7)
            DLCC_rate = (DLCC / total_output * 100) if total_output else 0

            # 打印处理后的数据
            print(f"总产量: {total_output}")
            print(f"正常产出: {normal_output}")
            print(f"正常产出占比: {normal_rate:.2f}%")
            print(f"平均效率: {avg_efficiency:.3f}%")
            print(f"入库效率: {storage_efficiency:.3f}%")
            print(f"合并档产出: {merge_output}")
            print(f"合并档产出占比: {merge_rate:.2f}%")
            print(f"漏电合并档产出: {leak_output}")
            print(f"漏电合并档产出占比: {leak_output_rate:.3f}%")
            print(f"漏电失效产出: {leak_fail}")
            print(f"漏电失效产出占比: {leak_fail_rate:.4f}%")
            print(f"DLCC 产出: {DLCC}")
            print(f"DLCC 产出占比: {DLCC_rate:.2f}%")

            # 准备提交的数据
            submit_data = {
                "date": formatted_date,
                "shift": shift,
                "BinFileName": product,
                "sum_IvGrade": total_output,
                "avg_eta": round(avg_efficiency, 3),
                "ru_eta": round(storage_efficiency, 3),
                "hbd": merge_output,
                "dlcc": DLCC,
                "IRev2_B": leak_output,
                "IRev2_Fail": leak_fail
            }

            # 发送 POST 请求提交数据
            submit_response = requests.post(SUBMIT_API_URL, json=submit_data)

            if submit_response.status_code == 200:
                print("数据提交成功")
            else:
                print(f"数据提交失败，状态码: {submit_response.status_code}")
        else:
            print(f"请求失败，状态码: {response.status_code}")
    except requests.RequestException as e:
        print(f"请求发生错误: {e}")

if __name__ == "__main__":
    process_api_data()
